// 撰写新闻

import React, { useState, useRef, useEffect } from 'react';
import { Steps, Button, Form, Input, Select, message, notification, FormInstance, Spin, Card } from 'antd';
import { PageHeader } from '@ant-design/pro-layout';
import { useNavigate, useParams } from 'react-router-dom';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { SaveOutlined, SendOutlined, ArrowLeftOutlined, ArrowRightOutlined } from '@ant-design/icons';
import NewsEditor from '../../../components/news-manage/NewsEditor';
import { addNews, getNewsById, updateNews, NewsItem } from '../../../api/newsApi';
import auth from '../../../utils/auth';
import { useCategories } from '../../../hooks/useCategories';
import { PublishState } from '../../../types/news';
import { News } from '../../../types';
import './News.scss';

const { Step } = Steps;

// 新闻表单数据接口
interface NewsFormData {
  title: string;
  categoryId: string | number;
}

// 新闻提交数据接口
interface NewsSubmitData extends Partial<News> {
  title: string;
  categoryId: string | number; // 支持字符串(MongoDB ObjectId)或数字
  content: string;
  region: string;
  author: string;
  roleId: number;
  auditState: number;
  publishState: number;
  createTime: number;
  star: number;
  view: number;
}

// 新闻组件
const NewsAdd: React.FC = () => {
  // 获取路由参数，用于判断是新增还是编辑
  const { id } = useParams<{ id?: string }>();
  const isUpdateMode = !!id;

  const [current, setCurrent] = useState<number>(0);
  const [formInfo, setFormInfo] = useState<NewsFormData>({} as NewsFormData);
  const [content, setContent] = useState<string>("");
  const navigate = useNavigate();
  const newsForm = useRef<FormInstance>(null); // Form 组件的 ref
  const [autoSaving, setAutoSaving] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(true);
  const [newsData, setNewsData] = useState<News | null>(null);

  // 使用安全的方式获取用户信息
  const userInfo = auth.getUserInfo() || {
    username: '未知用户',
    region: '未知区域',
    roleId: 0
  };
  const queryClient = useQueryClient();

  // 获取分类列表
  const { categories, loading: isCategoriesLoading } = useCategories();

  // 获取新闻详情（编辑模式）
  useEffect(() => {
    const fetchNewsData = async () => {
      if (isUpdateMode && id) {
        try {
          const news = await getNewsById(id);
          if (news) {
            const newsData = news as NewsItem;
            setNewsData(newsData as News);
            
            // 计算分类ID
            const categoryId = typeof newsData.category === 'object' 
              ? newsData.category.id 
              : newsData.category || '';
            
            // 设置表单初始值
            if (newsForm.current) {
              newsForm.current.setFieldsValue({
                title: newsData.title || '',
                categoryId: categoryId
              });
            }
            
            // 设置表单数据
            const formData = {
              title: newsData.title || '',
              categoryId: categoryId
            };
            
            setFormInfo(formData);
            setContent(newsData.content || "");
          } else {
            message.error('获取新闻详情失败');
            navigate('/news-manage/draft');
          }
        } catch (error) {
          console.error('获取新闻详情错误:', error);
          message.error('获取新闻详情失败');
          navigate('/news-manage/draft');
        }
      }
      setLoading(false);
    };

    fetchNewsData();
  }, [id, isUpdateMode, navigate]);

  // 当分类数据加载完成时更新loading状态
  useEffect(() => {
    if (!isUpdateMode && categories) {
      setLoading(false);
    }
  }, [categories, isUpdateMode]);

  // 添加新闻
  const addNewsMutation = useMutation({
    mutationFn: (data: NewsSubmitData) => addNews(data),
    onSuccess: (_, variables) => {
      const { auditState } = variables;
      
      // 清除localStorage中保存的草稿
      localStorage.removeItem('news_draft');
      
      // 更新正确的查询缓存
      queryClient.invalidateQueries({ queryKey: ['news', 'draft', userInfo.username] });
      queryClient.invalidateQueries({ queryKey: ['news'] });
      
      // 根据状态跳转到不同页面并显示通知
      if (auditState === 0) {
        navigate('/news-manage/draft');
        notification.success({
          message: '保存成功',
          description: '新闻已保存到草稿箱',
          placement: 'bottomRight'
        });
      } else {
        navigate('/audit-manage/list');
        notification.success({
          message: '提交成功',
          description: '新闻已提交审核',
          placement: 'bottomRight'
        });
      }
    },
    onError: (error: Error | unknown) => {
      // 处理特殊情况：如果错误信息包含"成功"，可能是后端返回了成功但被当作错误处理
      if (
        error instanceof Error && 
        error.message && 
        error.message.includes('成功')
      ) {
        const { auditState } = addNewsMutation.variables as NewsSubmitData;
        
        // 清除localStorage中保存的草稿
        localStorage.removeItem('news_draft');
        
        // 更新相关查询缓存
        queryClient.invalidateQueries({ queryKey: ['news', 'draft', userInfo.username] });
        queryClient.invalidateQueries({ queryKey: ['news'] });
        
        // 仍然按照成功处理，根据状态跳转到不同页面
        if (auditState === 0) {
          navigate('/news-manage/draft');
          notification.success({
            message: '保存成功',
            description: '新闻已保存到草稿箱',
            placement: 'bottomRight'
          });
        } else {
          navigate('/audit-manage/list');
          notification.success({
            message: '提交成功',
            description: '新闻已提交审核',
            placement: 'bottomRight'
          });
        }
        return;
      }
      
      // 处理实际错误
      console.error("新闻添加失败:", error);
      notification.error({
        message: '操作失败',
        description: '请稍后重试',
        placement: 'bottomRight'
      });
    }
  });

  // 更新新闻
  const updateNewsMutation = useMutation({
    mutationFn: (data: { id: string, news: Partial<News> }) => updateNews(data.id, data.news),
    onSuccess: (_, variables) => {
      const { news } = variables;
      const auditState = news.auditState || 0;
      
      // 更新正确的查询缓存
      queryClient.invalidateQueries({ queryKey: ['news', 'draft', userInfo.username] });
      queryClient.invalidateQueries({ queryKey: ['news'] });
      
      // 根据状态跳转到不同页面并显示通知
      if (auditState === 0) {
        navigate('/news-manage/draft');
        notification.success({
          message: '更新成功',
          description: '新闻已更新并保存到草稿箱',
          placement: 'bottomRight'
        });
      } else {
        navigate('/audit-manage/list');
        notification.success({
          message: '提交成功',
          description: '新闻已更新并提交审核',
          placement: 'bottomRight'
        });
      }
    },
    onError: (error: Error | unknown) => {
      // 处理特殊情况：如果错误信息包含"成功"，可能是后端返回了成功但被当作错误处理
      if (
        error instanceof Error && 
        error.message && 
        error.message.includes('成功')
      ) {
        const { news } = updateNewsMutation.variables as { news: Partial<News> };
        const auditState = news.auditState || 0;
        
        // 更新相关查询缓存
        queryClient.invalidateQueries({ queryKey: ['news', 'draft', userInfo.username] });
        queryClient.invalidateQueries({ queryKey: ['news'] });
        
        // 仍然按照成功处理，根据状态跳转到不同页面
        if (auditState === 0) {
          navigate('/news-manage/draft');
          notification.success({
            message: '更新成功',
            description: '新闻已更新并保存到草稿箱',
            placement: 'bottomRight'
          });
        } else {
          navigate('/audit-manage/list');
          notification.success({
            message: '提交成功',
            description: '新闻已更新并提交审核',
            placement: 'bottomRight'
          });
        }
        return;
      }
      
      // 处理实际错误
      console.error("新闻更新失败:", error);
      notification.error({
        message: '操作失败',
        description: '请稍后重试',
        placement: 'bottomRight'
      });
    }
  });

  // 表单布局
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };

  // 下一步
  const handleNext = () => {
    if (current === 0) {
      newsForm.current?.validateFields()
        .then((values: NewsFormData) => {
          setFormInfo(values);
          setCurrent(current + 1);
        })
        .catch((error: unknown) => {
          console.log(error);
        });
    } else {
      if (content === "" || content.trim() === "<p></p>") {
        message.error("新闻内容不能为空");
      } else {
        setCurrent(current + 1);
      }
    }
  };

  // 上一步
  const handlePrevious = () => {
    setCurrent(current - 1);
  };

  // 保存或提交
  const handleSave = (auditState: number) => {
    // 准备提交数据
    const submitData: NewsSubmitData = {
      ...formInfo,
      content,
      region: userInfo.region ? String(userInfo.region) : "工作室",
      author: String(userInfo.username),
      roleId: Number(userInfo.roleId),
      auditState,
      publishState: PublishState.UNPUBLISHED, // 使用统一的枚举常量
      createTime: newsData?.createTime || Date.now(),
      star: newsData?.star || 0,
      view: newsData?.view || 0,
      // 使用原始categoryId，不做数字转换，以兼容MongoDB的ObjectId
      categoryId: formInfo.categoryId
    };
    
    if (isUpdateMode && id) {
      // 更新新闻
      console.log('更新新闻数据:', submitData);
      updateNewsMutation.mutate({ 
        id, 
        news: submitData 
      });
    } else {
      // 添加新闻
      console.log('提交新闻数据:', submitData);
      addNewsMutation.mutate(submitData);
    }
  };

  // 处理自动保存的逻辑
  useEffect(() => {
    let autoSaveTimer: NodeJS.Timeout;
    
    if (autoSaving) {
      // 设置定时器在2秒后关闭自动保存提示
      autoSaveTimer = setTimeout(() => {
        setAutoSaving(false);
      }, 2000);
    }
    
    // 清理函数，组件卸载时清除定时器
    return () => {
      if (autoSaveTimer) {
        clearTimeout(autoSaveTimer);
      }
    };
  }, [autoSaving]);

  // 处理表单值变化
  const handleFormValuesChange = () => {
    // 如果表单值发生变化，显示正在自动保存的提示
    setAutoSaving(true);
  };

  // 处理分类选择变化
  const handleCategoryChange = (value: string) => {
    console.log('选择的分类ID:', value);
    setAutoSaving(true);
  };

  // 显示加载状态
  if (isCategoriesLoading || loading) {
    return (
      <div className="loading-container">
        <Spin tip="加载中..." size="large" />
      </div>
    );
  }

  return (
    <div className="news-container">
      <PageHeader
        className="page-header"
        title={isUpdateMode ? "编辑新闻" : "撰写新闻"}
        subTitle={isUpdateMode ? "更新现有新闻" : "创建并发布新闻"}
        onBack={() => navigate(-1)}
      />
      
      <Spin spinning={loading}>
        <Card className="news-card">
          <Steps className="steps-container" current={current}>
            <Step title="基本信息" description="新闻标题、分类" />
            <Step title="新闻内容" description="主体内容" />
            <Step title="提交" description="保存或提交审核" />
          </Steps>

          {/* 第一步：基本信息 */}
          {current === 0 && (
            <div className="step-content-container">
              <Form
                {...layout}
                ref={newsForm}
                name="news_form"
                className="basic-info-form"
                initialValues={{ title: formInfo.title, categoryId: formInfo.categoryId }}
                onValuesChange={handleFormValuesChange}
              >
                <Form.Item
                  name="title"
                  label="新闻标题"
                  rules={[{ required: true, message: '请输入新闻标题' }]}
                >
                  <Input placeholder="请输入新闻标题" />
                </Form.Item>

                <Form.Item
                  name="categoryId"
                  label="新闻分类"
                  rules={[{ required: true, message: '请选择新闻分类' }]}
                >
                  <Select
                    placeholder="请选择新闻分类"
                    loading={isCategoriesLoading}
                    onChange={handleCategoryChange}
                  >
                    {categories?.map(item => {
                      // 安全获取分类标题
                      const getCategoryTitle = () => {
                        // 处理可能的MongoDB文档结构
                        const mongoDoc = item as unknown as { _doc?: { title: string } };
                        return mongoDoc._doc?.title || item.title || '未命名分类';
                      };
                      
                      return (
                        <Select.Option key={item.id} value={item.id}>
                          {getCategoryTitle()}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              </Form>
            </div>
          )}

          {/* 第二步：新闻内容 */}
          {current === 1 && (
            <div className="step-content-container editor-step-container">
              <NewsEditor 
                content={content}
                getContent={(htmlContent) => {
                  setContent(htmlContent);
                  // 自动保存草稿
                  localStorage.setItem('news_draft', JSON.stringify({
                    ...formInfo,
                    content: htmlContent,
                    timestamp: Date.now()
                  }));
                }}
              />
            </div>
          )}
            
          {/* 第三步：提交 */}
          {current === 2 && (
            <div className="step-content-container preview-step-container">
              <Card className="preview-card">
                <h2 className="preview-title">{formInfo.title}</h2>
                <div dangerouslySetInnerHTML={{ __html: content }} className="news-preview-content"></div>
              </Card>
            </div>
          )}

          {/* 底部操作区域 */}
          <div className="bottom-actions">
            <div className="left-actions">
              {current > 0 && (
                <Button type="primary" icon={<ArrowLeftOutlined />} onClick={handlePrevious}>
                  上一步
                </Button>
              )}
            </div>
            
            <div className="right-actions">
              {autoSaving && (
                <span className="auto-save-indicator">
                  <Spin size="small" style={{ marginRight: 8 }} />
                  正在自动保存...
                </span>
              )}
              
              {current < 2 && (
                <Button type="primary" onClick={handleNext} icon={<ArrowRightOutlined />}>
                  下一步
                </Button>
              )}
              
              {current === 2 && (
                <>
                  <Button onClick={() => handleSave(0)} icon={<SaveOutlined />}>
                    保存草稿
                  </Button>
                  <Button type="primary" onClick={() => handleSave(1)} icon={<SendOutlined />} style={{ marginLeft: 8 }}>
                    提交审核
                  </Button>
                </>
              )}
            </div>
          </div>
        </Card>
      </Spin>
    </div>
  );
};

export default NewsAdd; 